package com.api.user.controller;

import com.api.common.EmailUtil;
import com.api.core.annotation.PowerEnable;
import com.api.core.controller.Ctrl;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.api.user.enums.IdentificationStatusEnums;
import com.api.user.model.ManageExamineLog;
import com.api.user.model.ManageInfo;
import com.api.user.model.UserInfo;
import com.api.user.service.ManageInfoService;
import com.api.user.service.UserInfoService;
import io.swagger.annotations.*;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by wanghuiwen on 2021/03/25.
 */
@PowerEnable(name = "ManageInfo", url = "/manage/info")
@Api(value = "ManageInfo", tags = {"ManageInfo"})
@RestController
@RequestMapping("/manage/info")
public class ManageInfoController extends Ctrl {
    @Resource
    private ManageInfoService manageInfoService;
    @Resource
    private UserInfoService userInfoService;

    @ApiOperation(value = "主持人申请", tags = {"ManageInfo"}, notes = "主持人申请")
    @PostMapping(value = "/save", name = "主持人申请")
    public Result save(@RequestBody ManageInfo manageInfo, Authentication authentication) {
        Long userId = getAuthUser(authentication).getId();
        manageInfo.setUserId(userId);
        manageInfo.setExamine(IdentificationStatusEnums.ADOPT);
        manageInfoService.add(manageInfo);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "审核主持人", tags = {"ManageInfo"}, notes = "审核主持人")
    @PostMapping(value = "/examine", name = "审核主持人")
    public Result examine(@ApiParam ManageExamineLog manageExamineLog, Authentication authentication) {
        Long userId = getAuthUser(authentication).getId();
        manageExamineLog.setUserId(userId);
        return manageInfoService.examine(manageExamineLog);
    }

    @ApiOperation(value = "主持人列表", tags = {"ManageInfo"}, notes = "主持人列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "phoneNumber", value = "手机号码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "examine", value = "审核状态", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fullName", value = "用户名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "order", value = "排序json", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数", dataType = "String", paramType = "query", defaultValue = "10")
    })
    @PostMapping(value = "/list", name = "主持人列表")
    public Result user(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) Long examine,
            @RequestParam(required = false) String fullName,
            @RequestParam(required = false) String block,
            @RequestParam(defaultValue = "{}") String order,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("phoneNumber", phoneNumber);
        params.put("examine", examine);
        params.put("fullName", fullName);
        params.put("block", block);


        return manageInfoService.list(params, order, page, size);
    }

    @PostMapping(value = "/export", name = "导出")
    public void export(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) Long examine,
            @RequestParam(required = false) String fullName,
            @RequestParam(required = false) String block,
            @RequestParam(defaultValue = "{}") String order,
            HttpServletResponse response) throws IOException {

        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("phoneNumber", phoneNumber);
        params.put("examine", examine);
        params.put("fullName", fullName);
        params.put("block", block);
        List<Map<String, Object>> res =  manageInfoService.export(params, order);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("用户信息");
        // 设置要导出的文件的名字
        String fileName = "mmc_users"  + new Date() + ".xls";
        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        String[] headers = { "ID","User Name", "Company Email", "Contact Number", "Company Type","Tournament"};
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //在表中存放查询到的数据放入对应的列
        for (Map<String, Object> item : res) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(getValue(item.get("userId")));
            row1.createCell(1).setCellValue(getValue(item.get("fullName")));
            row1.createCell(2).setCellValue( getValue(item.get("companyEmail")));
            row1.createCell(3).setCellValue(getValue(item.get("contactNumber")));
            row1.createCell(4).setCellValue(getValue(item.get("compamyType")));
            row1.createCell(5).setCellValue(getValue(item.get("tournament")));
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
    private String getValue(Object value){
        return value!=null ?value.toString() : "";
    }

    @ApiOperation(value = "主持人详情", tags = {"ManageInfo"}, notes = "主持人详情")
    @PostMapping(value = "/detail", name = "主持人申请")
    public Result detail(Long userId) {
        return manageInfoService.detail(userId);
    }

    @ApiOperation(value = "主持人修改", tags = {"ManageInfo"}, notes = "主持人修改")
    @PostMapping(value = "/update", name = "主持人申请")
    public Result update(Long userId,
                         String fullName,
                         String gender,
                         String phoneNumber,
                         String email,
                         String nationality,
                         String addressDetail,
                         String addressCountry,
                         String addressState,
                         String postcode,
                         String aboutOrganizer,
                         String companyName,
                         String companyRegistrationNumber,
                         String street) {
        UserInfo userInfo = userInfoService.findById(userId);
        if (userInfo == null) return ResultGenerator.genFailResult(400, "User does not exist");
        userInfo.setFullName(fullName);
        userInfo.setGender(gender);
        userInfo.setPhoneNumber(phoneNumber);
        userInfo.setEmail(email);
        userInfo.setNationality(nationality);
        userInfo.setAddressDetail(addressDetail);
        userInfo.setAddressCountry(addressCountry);
        userInfo.setAddressState(addressState);
        userInfo.setPostcode(postcode);
        userInfo.setVipLevel(IdentificationStatusEnums.USER_LEVEL_BASE);
        ManageInfo manageInfo = manageInfoService.findById(userId);
        if (manageInfo == null) {
            manageInfo = new ManageInfo();
        }
        manageInfo.setAboutOrganizer(aboutOrganizer);
        manageInfo.setCompanyName(companyName);
        manageInfo.setCompanyRegistrationNumber(companyRegistrationNumber);
        manageInfo.setStreet(street);
        return manageInfoService.updateManager(userInfo, manageInfo);
    }

    @PostMapping(value = "/invitation/list", name = "主持人邀请列表")
    public Result invitation(Authentication authentication) {
        return manageInfoService.invitation(getAuthUser(authentication));
    }

    @PostMapping(value = "/invitation", name = "主持人邀请")
    public Result invitation(String email,String fullName,String password,Authentication authentication) {
        Result result = manageInfoService.invita(email,fullName,password,getAuthUser(authentication));
        if(result.getCode() == 200){
            EmailUtil.gmailSender(email,"Hi, your organizer has sent you a request to join our him to co-organize a tournament together.\n" +
                    "Here your login details:\n" +
                    "Platform link: \n" +
                    "ID:" + email +
                    "Password:" + password,null);
        }
        return result;
    }

    @PostMapping(value = "/invitation/disable", name = "主持人禁用邀请")
    public Result invitationRemove(Long userId,@RequestParam(defaultValue = "true") Boolean disable) {
        return manageInfoService.invitationRemove(userId,disable);
    }



    @PostMapping(value = "/block", name = "主持人禁用邀请")
    public Result block(Long userId,Boolean block) {
        return manageInfoService.block(userId,block);
    }
}


